import React, {Component} from 'react'
import {Tabs} from 'antd';
import {withRouter} from 'react-router-dom';
import {connect} from 'react-redux';
import {addTab,removeTab} from '../../redux/main.redux';
import './TabContent.scss';
const TabPane = Tabs.TabPane;
@withRouter
@connect(state => state.navsidelist || {}, {addTab,removeTab})
class TabContent extends Component {
  constructor(props) {
    super(props);
    this.newTabIndex = 0;
    const panes = [];
    this.state = {
      activeKey: null,
      panes
    };
  }

  onChange = (activeKey) => {
    this._forAddTab(this.props.navlist,activeKey)
    this.props.history.push(activeKey)
  }
  onEdit = (targetKey, action) => {
    this.props.removeTab(targetKey);
    let urlPath = null
    this.props.panes.forEach(v => {
      // 删除最后一个的时候 js加载顺序问题 所以要判断不能等于当前的keys
      if(v.isOpen && v.url !== targetKey) {
        urlPath = v.url
      }
    })
    this.props.history.push(urlPath)
  }
  _forAddTab(navlist,item) {
    this._forTemplate(navlist,item)
  }

  _forTemplate(objectD,item) {
      let title = '';
      let key = '';
      let _retUrl = '';
      let icon = '';
      if(objectD.length > 0) {
        objectD.forEach((obj,i) => {
          if(obj.child) {
            obj.children.forEach(v => {
              if (item === v.url) {
                return (title = v.name, key = v.url, _retUrl=v.url,icon=v.icon,this.props.addTab({title,key,url:_retUrl,icon,isOpen: item.isOpen}))
              } else if(v.child){
                this._forTemplate([v],item)
              }
            })
          }
          if(obj.url === item) {
            return (title = obj.name, key = obj.url, _retUrl=obj.url,icon=obj.icon,this.props.addTab({title,key,url:_retUrl,icon,isOpen: item.isOpen}))
          }
      })
    }
  }
  componentWillRecevieProps(nextP) {
    console.log(nextP)
  }
  render() {
    const {panes} = this.props;
    let active = '/main'
    panes.map(v => v.isOpen ? active = v.url : null)
    return panes.length > 0 ? (
      <div className="card-container">
        <Tabs
          hideAdd
          onChange={this.onChange}
          activeKey={active}
          type="editable-card"
          onEdit={this.onEdit}>
          {this.props.panes.map((pane,index) => <TabPane routerPath={pane.url} tab={pane.icon ?<span className={index===0? 'none-one-tab' : null}><i className={`fa fa-icon-tab-menu fa-${pane.icon}`}></i>{pane.title}</span>: pane.title} key={pane.url} />)}
        </Tabs>
      </div>
    ): null
  }
}

export default TabContent
